/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.cursoexperto.jftf.carrocompra.backing;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.cursoexperto.jftf.carrocompra.entidades.Cliente;
import org.cursoexperto.jftf.carrocompra.services.ClienteService;
import org.cursoexperto.jftf.carrocompra.services.exceptions.NonexistentEntityException;
import org.cursoexperto.jftf.carrocompra.services.exceptions.PreexistingEntityException;


/**
 *
 * @author Jose Fernando
 */
public class LoginBean {

    /** Creates a new instance of LoginBean */

    private boolean logged;
    private String usuario;
    private String password;
    private Cliente cliente;

    public LoginBean() {
        logged = false;
    }

    /**
     * @return the logged
     */
    public boolean isLogged() {
        return logged;
    }

    /**
     * @param logged the logged to set
     */
    public void setLogged(boolean logged) {
        this.logged = logged;
    }

    /**
     * @return the cliente
     */
    public Cliente getCliente() {
        return cliente;
    }

    /**
     * @param cliente the cliente to set
     */
    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    /**
     * @return the usuario
     */
    public String getUsuario() {
        return usuario;
    }

    /**
     * @param usuario the usuario to set
     */
    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    public String login(){
        ClienteService cliServ = new ClienteService();
        Cliente cli = cliServ.findByUsuario(getUsuario());
        if(cli!=null){
            if(cli.getPassword().equals(password)){
                setLogged(true);
                setCliente(cli);
            }
        }
        return "login";
    }

    public String logout(){
        if(isLogged()){
            setLogged(false);
            setCliente(null);
        }
        return "login";
    }

    public String cambiaPassword(){
        ClienteService cliServ = new ClienteService();
        Cliente cli = cliServ.findByUsuario("rocio");
        cli.setPassword(getPassword());
        try {
            cliServ.edit(cli);
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "login";
    }

}
